﻿using System;
using MediatR;
using Casamiel.Domain.Response;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.Extensions.Options;
using Casamiel.Common;
using Casamiel.Domain;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Casamiel.Common.Extensions;
using System.Globalization;
using Enyim.Caching;

namespace Casamiel.Application.Commands
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class BindCouponCommandHandler : BaseCommandHandler, IRequestHandler<BindCouponCommand, BaseResult<string>>
	{
		private readonly IMemberRepository _memberRepository;
		private readonly IMemberCouponRepository _memberCouponRepository;
		private readonly IMemcachedClient _memcachedClient;
		private readonly string _memcachedPrex;
		public BindCouponCommandHandler(IMemberRepository memberRepository, IMemberCouponRepository memberCouponRepositor, INetICService netICService,
			IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings, IMemcachedClient memcachedClient) : base(netICService, httpClientFactory, settings)

		{
			_memberRepository = memberRepository;
			_memberCouponRepository = memberCouponRepositor;
			_memcachedClient = memcachedClient;
			_memcachedPrex = settings.Value.MemcachedPre;

		}

		public async Task<BaseResult<string>> Handle(BindCouponCommand request, CancellationToken cancellationToken)
		{
			if (request is null) {
				throw new ArgumentNullException(nameof(request));
			}
			var entity = await _memberRepository.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
			if (entity == null) {
				return new BaseResult<string>("", 9999, "会员不存在");
			}
			var _cachekey = _memcachedPrex + Constant.BINDCOUPON + request.Ticketcode.Trim();

			var trynum = _memcachedClient.Increment(_cachekey, 1, 1);

			var coupon = await _memberCouponRepository.FindAsync<ICasaMielSession>(request.Ticketcode.Trim()).ConfigureAwait(false);
			if (coupon != null) {
				return new BaseResult<string>("",999, "券已被绑定");
			}
			if (trynum > 1) {
				var t = await _memberCouponRepository.FindAsync<ICasaMielSession>(request.Ticketcode.Trim()).ConfigureAwait(false);
				if (t != null) {
					return new BaseResult<string>("", 0,"");
				}
				return new BaseResult<string>("", 999, "请重试");
			}
			try {

				var icresult = await NetICService.Tmticketchange(new Domain.Request.TmticketchangeRequest { Ticketcode = request.Ticketcode }).ConfigureAwait(false);
				if (icresult.code == 0) {
					//{"code":0,"content":"{\"newticketid\":58589790,\"newticketcode\":\"383836883066537215\",\"ticketid\":58589789,\"ticketcode\":\"305888238862533476\"}"
					var d = JObject.Parse(icresult.content);
					var a = new MemberCoupon {
						CreateTime = DateTime.Now,
						GiveStatus = (int)GiveStatus.CanGive,
						OldTicketcode = request.Ticketcode,
						Ticketcode = d["newticketcode"].ToString(),
						MID = entity.ID
					};

					var ticketInfoRsp = await NetICService.Tmticketquery(new Domain.Request.IC.TmticketqueryReq { ticketcode = a.Ticketcode }).ConfigureAwait(false);
					if (ticketInfoRsp.code == 0) {
						//"content": "{\"wxopenid\":\"\",\"ticketcode\":\"383836883066537215\",\"productid\",278048,\"productname\":\"蜜兒10元提货券(160*65)mm\",\"customername\":\"招银网络科技（深圳）有限公司\",\"price\":10.00,\"state\":3,\"description\":\"可使用\",\"startdate\":\"2019-04-02 00:00:00\",\"enddate\":\"2022-06-29 23:59:55\"}",
						var ticketInfo = JObject.Parse(ticketInfoRsp.content);

						a.Price = ticketInfo["price"].ToString().ToDecimal(0);
						a.Productname = ticketInfo["productname"].ToString();
						a.Productid = ticketInfo["productid"].ToInt64(0);
						a.State = ticketInfo["state"].ToInt16(0);
						a.Startdate = DateTime.Parse(ticketInfo["startdate"].ToString(), CultureInfo.InvariantCulture);
						a.Enddate = DateTime.Parse(ticketInfo["enddate"].ToString(), CultureInfo.InvariantCulture);

					}
					await _memberCouponRepository.SaveAsync<ICasaMielSession>(a).ConfigureAwait(false);
					return new BaseResult<string>("", icresult.code, icresult.msg);
				}
				_memcachedClient.Remove(_cachekey);
				return new BaseResult<string>("", icresult.code, icresult.msg);
			} catch (Exception ex) {
				_memcachedClient.Remove(_cachekey);
				LoggerSystemErrorInfo.Error($"BindCoupon：{ ex.StackTrace}");
				return new BaseResult<string>("", 9999, "BindCoupon出错了");
			}

		}
	}
}
